package co.yixiang.hw.utils;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;


/**
 * 封装对外访问方法
 * @author liuyazhuang
 *
 */
public class WXCore {

    private static final String WATERMARK = "watermark";
    private static final String APPID = "appid";
    /**
     * 解密数据
     * @return
     * @throws Exception
     */
    public static String decrypt(String appId, String encryptedData, String sessionKey, String iv){
        String result = "";
        try {
            AES aes = new AES();
            byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
            if(null != resultByte && resultByte.length > 0){
                result = new String(WxPKCS7Encoder.decode(resultByte));
                JSONObject jsonObject = JSONObject.parseObject(result);
                String decryptAppid = jsonObject.getJSONObject(WATERMARK).getString(APPID);
                if(!appId.equals(decryptAppid)){
                    result = "";
                }
            }
        } catch (Exception e) {
            result = "";
            e.printStackTrace();
        }
        return result;
    }

//    参数：{"appid":"wx44031547d2d62ced","js_code":"013L9Jkl21BiL64ceRml2rvZOA1L9JkV","secret":"ae02af89067c92af227c347150aadf94"}
//    结果：{"session_key":"PEAV39EhFNpxUU65MdYfTA==","openid":"oP5Lw4nO9QsnyXeWKKlD8cMclkc8"}
// 参数：{"code":"013L9Jkl21BiL64ceRml2rvZOA1L9JkV","encrypdata":"1izsSnZ3j2rnB/RD6p7SjdBWR4fspV/B9Por92O6Zh3okz/TstyZY5PaYmWt37IYRdFMNhPvirdwxV5qGIqVI3v96k5WY6rQAQw03QLJHt9Op7UaCtlk/nASpseIAlC0nSvCqhwBVE450moPUNnqh722JqqFB6J4YzAm4YdyRdmOa+mam8FtBNQo0w5e6Ru83bfsc1AF4XsGYPqVO4glFg==","ivdata":"gxEimIU/RbOrJoFQpj06jw=="}
//    结果：

    public static void main(String[] args) throws Exception{
        String appId = "wxd4f4b7bedf2bdd43";
        String encryptedData = "1izsSnZ3j2rnB/RD6p7SjdBWR4fspV/B9Por92O6Zh3okz/TstyZY5PaYmWt37IYRdFMNhPvirdwxV5qGIqVI3v96k5WY6rQAQw03QLJHt9Op7UaCtlk/nASpseIAlC0nSvCqhwBVE450moPUNnqh722JqqFB6J4YzAm4YdyRdmOa+mam8FtBNQo0w5e6Ru83bfsc1AF4XsGYPqVO4glFg==";
        String sessionKey = "PEAV39EhFNpxUU65MdYfTA==";
        String iv = "gxEimIU/RbOrJoFQpj06jw==";
        System.out.println(decrypt(appId, encryptedData, sessionKey, iv));
    }
}
